package com.dsr.service.impl;

import com.dsr.consts.PageResult;
import com.dsr.consts.Result;
import com.dsr.dao.FlowerVoDao;
import com.dsr.dao.SectionVoDao;
import com.dsr.entity.Flower;
import com.dsr.entity.Spit;
import com.dsr.service.SearchService;
import com.dsr.vo.FlowerVO;
import com.dsr.vo.SectionVO;
import org.apache.commons.collections.IteratorUtils;
import org.elasticsearch.index.query.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import  org.elasticsearch.index.query.QueryBuilders;

/**
 * @author dsr
 * @since 2020-10-10
 */
@Service("searchService")
public class SearchServiceImpl implements SearchService {

    @Autowired
    private FlowerVoDao flowerVoDao;
    @Autowired
    private SectionVoDao sectionVoDao;
    @Override
    public Result search(Map<String, String> keyMap) {
        //构建查询对象
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        List<SectionVO> sectionVOList=new ArrayList<>();
        // 更具关键字构建title和description搜索
        if(keyMap.containsKey("keyword")){
            //查询分类是否关键字字段
            sectionVOList= sectionVoDao.findByNameLike(keyMap.get("keyword"));
            //全文检索 使用或查询（Operator.OR）
            MatchQueryBuilder titleQuery = QueryBuilders.matchQuery("title", keyMap.get("keyword")).operator(Operator.OR);
            MatchQueryBuilder descriptionQuery = QueryBuilders.matchQuery("description", keyMap.get("keyword")).operator(Operator.OR);
            queryBuilder.should(titleQuery).should(descriptionQuery);
        }
        //更具关键字查询的分类id匹配查询字段
        if (sectionVOList.size()>0){
            String collect=".*"+sectionVOList.stream().map(SectionVO::getId).collect(Collectors.joining(".*|.*"))+".*";
            RegexpQueryBuilder matchQuery = QueryBuilders.regexpQuery("section", collect);
            queryBuilder.should(matchQuery);
            System.out.println(collect);

        }
        // 上面的条件是全文检索，使用或（should）并列查询
        //是否在执行分类筛选
        if(keyMap.containsKey("sectionIds")){
            String[] sectionIds = keyMap.get("sectionIds").split(",");
            //分类筛选是并且的关系使用must
            for (String sectionId : sectionIds) {
                String collect=".*"+sectionId+".*";
                QueryBuilder section = QueryBuilders.regexpQuery("section", collect);
                queryBuilder.must(section);
            }
        }
        queryBuilder.mustNot(QueryBuilders.termQuery("del", "1"));
        Iterable<FlowerVO> search = flowerVoDao.search(queryBuilder);
        System.out.println(queryBuilder.toString());
        return Result.success(getList(IteratorUtils.toList(search.iterator())));
    }

    @Override
    public Result getFlowerBySection(String sectionId) {
        RegexpQueryBuilder matchQuery = QueryBuilders.regexpQuery("section", ".*" + sectionId + ".*");
        Iterable<FlowerVO> search = flowerVoDao.search(matchQuery);
        return Result.success(getList(IteratorUtils.toList(search.iterator())));
    }

    @Override
    public Result query(int page, int size, Flower flower) {
        Sort.Order updateDate = Sort.Order.desc("updateDate");
        Sort sort = Sort.by(updateDate);
        Pageable pageable = PageRequest.of(page-1, size,sort);
        Page<FlowerVO> all = flowerVoDao.findAll(pageable);
        return Result.success(new PageResult<FlowerVO>(all.getTotalElements(),getList(all.getContent())));
    }

    private List getList(List<FlowerVO> list ){
        list.forEach(item->{
            if (item.getImgUrl().contains(",")) {
                String[] split = item.getImgUrl().split(",");
                item.setImgUrl(split[0]);
            }else {
                item.setImgUrl(item.getImgUrl());
            }
        });
        return list;
    }

}
